import React, { useCallback, useMemo, useState } from 'react';
import { Modal, Table, Button, message, Input, Empty } from 'antd';
import MemberSelectCore, {
  getMemberIconByKey,
} from '@inbiz/basic/MemberSelect';
import '../../../style.less';
import {
  addMenuButtonPerm,
  addModelPerm,
  deletePermission,
  delMenuButtonPerm,
  delModelPerm,
  editMenuButtonPerm,
  editModelPerm,
  postPermission,
  putPermission,
} from '../../../service';
import {
  CheckOutlined,
  CloseOutlined,
  DeleteOutlined,
  EditOutlined,
  EyeOutlined,
  PlusOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import { getMessage, TextWidget } from '@inbiz/react';
import { observer } from '@formily/react';
import Pagination from '@inbiz/basic/Pagination';
import { useEffect } from 'react';

const Permission = observer((props: any) => {
  const {
    list,
    outId,
    menuId,
    onRefresh,
    permtype,
    menuOutId,
    parentId,
    permConfig,
  } = props;
  const [selectedRowKeys, $selectedRowKeys] = useState([]);
  const [pageSize, $pageSize] = useState(10);
  const [pageIndex, $pageIndex] = useState(1);
  const [dataSource, $dataSource] = useState([]);
  // 成员选择props
  const [visible, $visible] = useState(false);
  const [searchText, $searchText] = useState('');
  const memberSelectProps = useMemo(() => {
    let newprops: any = {
      visible,
      config: {
        multiple: true,
        selected: [],
        onCancel: () => $visible(false),
        onOk: (keys, rows) => {
          handleOk(rows);
          $visible(false);
        },
      },
    };
    newprops.config.tabs = permConfig.member;
    return newprops;
  }, [permConfig, props, visible]);

  // 成员选择确认
  const handleOk = (data) => {
    let addData = [];
    data.forEach((item) => {
      let obj: any = {
        MemberType: item.memberarea,
        MemberId: item.id,
        MemberName: item.name,
        Permission: {
          None: false,
          ReadOnly: false,
          Design: false,
          Manage: true,
        },
      };
      if (permtype != 'menu') {
        obj.permissionValue = 4;
        obj.permissionId = permtype == 'action' ? menuId : null;
      }
      if (item.memberarea == 3) {
        if (item.name == 'Creators') {
          obj.MemberType = 2;
        } else if (item.name == 'Everyone') {
          obj.MemberType = 6;
        }
      }
      addData.push(obj);
    });
    if (!addData.length) {
      message.error(getMessage('Permission.noMemberSelected'));
      return;
    }
    let payload: any = {
      permissions: addData,
      siteOutId: outId,
    };
    if (permtype != 'model') {
      payload.entityId = menuId;
    }
    if (permtype != 'menu') {
      payload.menuOutId = menuOutId;
      if (permtype == 'model') {
        payload.fieldName = menuId.split('&')[0];
        payload.type = menuId.split('&')[1];
        payload.modelKey = outId;
      }
    }
    permRequst(
      permtype == 'menu'
        ? postPermission
        : permtype == 'action'
          ? addMenuButtonPerm
          : addModelPerm,
      payload,
      getMessage('Permission.permissionAddedSuccessfully'),
    );
  };
  useEffect(() => {
    $dataSource((origin: any) => {
      return props.list.slice((pageIndex - 1) * pageSize, pageIndex * pageSize);
    });
  }, [props.list, pageIndex, pageSize]);
  // 表格props
  const tableProps = {
    dataSource: dataSource,
    columns: [
      {
        title: <TextWidget>Permission.name</TextWidget>,
        dataIndex: 'MemberName',
        key: 'MemberName',
        render: (text, record, index) => (
          <span>
            {getMemberIconByKey(record.MemberType)} {text}
          </span>
        ),
      },
      {
        title: <TextWidget>Permission.permissionStatus</TextWidget>,
        dataIndex: 'PermissionValue',
        key: 'PermissionValue',
        render: (text, record, index) => (
          <span>
            {permtype == 'model' && menuId?.split('&')[1] == '0' ? (
              record.PermissionValue > 1 ? (
                `${(<TextWidget>Permission.view</TextWidget>)},${(
                  <TextWidget>Permission.edit</TextWidget>
                )}`
              ) : (
                <TextWidget>Permission.view</TextWidget>
              )
            ) : record.PermissionValue > 0 ? (
              <TextWidget>Permission.HaveAuthority</TextWidget>
            ) : (
              <TextWidget>Permission.noPermission</TextWidget>
            )}
          </span>
        ),
      },
      {
        title: <TextWidget>Permission.type</TextWidget>,
        dataIndex: 'MemberType',
        key: 'MemberType',
        render: (text, record, index) => (
          <span>{changeUserType(record.MemberType).userType}</span>
        ),
      },
    ],
    bordered: true,
    rowKey: (record) => record.MemberId,
    rowSelection: {
      onChange: (selectedRowKeys, selectedRows) => {
        $selectedRowKeys(selectedRowKeys);
      },
      selectedRowKeys: selectedRowKeys,
    },
    pagination: false,
    locale: {
      emptyText: (
        <Empty
          className={'spindiv'}
          image={Empty.PRESENTED_IMAGE_SIMPLE}
          description={<TextWidget>Permission.noData</TextWidget>}
        />
      ),
    },
  };

  // getUserGroup
  const changeUserType = (type) => {
    let userType = '';
    let iconName = '';
    switch (type) {
      case 2:
      case 3:
      case 6:
        userType = getMessage('Permission.userGroup');
        iconName = 'icon-yonghuzu1';
        break;
      case 4:
        userType = getMessage('Permission.position');
        iconName = 'icon-zhiwei';
        break;
      case 5:
        userType = getMessage('Permission.department');
        iconName = 'icon-bumen';
        break;
      default:
        userType = getMessage('Permission.user');
        iconName = 'icon-yonghu1';
        break;
    }
    return {
      userType,
      iconName,
    };
  };

  // 删除用户
  const onDelete = () => {
    let permissionIds = [];
    list.forEach((item) => {
      if (selectedRowKeys.includes(item.MemberId)) {
        permissionIds.push(item.PermissionId);
      }
    });
    let payload: any;
    if (permtype == 'model') {
      payload = {
        menuOutId,
        modelKey: outId,
        fieldName: menuId.split('&')[0],
        deletModel: [
          {
            ids: permissionIds,
            type: menuId.split('&')[1],
          },
        ],
      };
    } else {
      payload = {
        entityId: menuId,
        permissionIds,
      };
    }
    Modal.confirm({
      title: getMessage('Permission.warning'),
      content: getMessage('Permission.areYouSureToDeleteTheSelectedMember'),
      okText: getMessage('Permission.determine'),
      cancelText: getMessage('Permission.cancel'),
      onOk() {
        permRequst(
          permtype == 'menu'
            ? deletePermission
            : permtype == 'action'
              ? delMenuButtonPerm
              : delModelPerm,
          payload,
          getMessage('Permission.memberDeletedSuccessfully'),
        );
        $selectedRowKeys([]);
      },
    });
  };

  // 编辑用户
  const onEditor = (status: boolean) => {
    let permissions = [];
    list.forEach((item) => {
      if (selectedRowKeys.includes(item.MemberId)) {
        let obj;
        obj = {
          ...item,
          Permission:
            permtype == 'model' && menuId?.split('&')[1] == '0'
              ? {
                None: false,
                Manage: false,
                ReadOnly: true,
                Design: status ? true : false,
              }
              : {
                None: status ? false : true,
                Manage: status ? true : false,
                ReadOnly: false,
                Design: false,
              },
          PermissionValue:
            permtype == 'model' && menuId?.split('&')[1] == '0'
              ? status
                ? 4
                : 1
              : item.permissionValue,
        };

        // if (permtype != 'menu') {
        //   obj.permissionValue = 4;
        //   obj.permissionId = permtype == 'action' ? menuId : null;
        // }
        permissions.push(obj);
      }
    });
    // 数据格式化
    let payload = {};
    if (permtype == 'menu') {
      payload = {
        params: {
          entityId: menuId,
        },
        data: {
          permissions,
          siteOutId: outId,
        },
      };
    } else if (permtype == 'action') {
      payload = {
        params: {
          entityId: menuId,
        },
        data: {
          permissions,
          menuOutId: menuOutId,
          parentId: parentId,
          siteOutId: outId,
        },
      };
    } else {
      payload = {
        params: {
          fieldName: menuId.split('&')[0],
        },
        data: {
          permissions,
          modelKey: outId,
          type: menuId.split('&')[1],
          fieldName: menuId.split('&')[0],
        },
      };
    }
    permRequst(
      permtype == 'menu'
        ? putPermission
        : permtype == 'action'
          ? editMenuButtonPerm
          : editModelPerm,
      payload,
      getMessage('Permission.permissionModifiedSuccessfully'),
    );
  };

  // 权限请求
  const permRequst = (ser: any, payload: {}, msg?: string) => {
    ser(payload).then((res: any) => {
      if (!res) return;
      if (msg) {
        message.success(msg);
      }
      onRefresh();
    });
  };

  // input.search Change赋值
  const onChangeSearch = useCallback((e) => {
    let searchText =
      e?.currentTarget?.value?.replace(/\ +/g, '') ||
      e?.target?.value?.replace(/\ +/g, '') ||
      '';
    $searchText(searchText);
  }, []);

  // 前端查询（过滤）
  const onSearch = useCallback(() => {
    onRefresh(searchText);
  }, [searchText]);

  const totalLang = getMessage('Permission.total');
  const itemsLang = getMessage('Permission.item');

  return (
    <div className={'permissinList'}>
      <div>
        <div
          style={{
            margin: '0px 0 10px 0',
            display: 'flex',
            justifyContent: 'space-between',
          }}
        >
          <div>
            {/* 添加 */}
            <Button
              onClick={() => {
                if (!menuId) {
                  message.error(
                    permtype == 'menu'
                      ? getMessage('Permission.noMenuSelected')
                      : permtype == 'action'
                        ? getMessage('Permission.noButtonSelected')
                        : getMessage('Permission.noModelFieldSelected'),
                  );
                  return;
                }
                $visible(true);
              }}
              icon={<PlusOutlined style={{ marginRight: '5px' }} />}
              type={'primary'}
              disabled={!menuId}
              style={{
                marginRight: '8px',
                marginBottom: '8px',
              }}
            >
              <TextWidget>Permission.addTo</TextWidget>
            </Button>
            <Button
              onClick={onDelete}
              icon={<DeleteOutlined style={{ marginRight: '5px' }} />}
              disabled={selectedRowKeys.length == 0}
              type={'danger'}
              style={{ marginRight: '8px' }}
            >
              <TextWidget>Permission.delete</TextWidget>
            </Button>
            <Button
              onClick={() => onEditor(true)}
              icon={
                permtype == 'model' && menuId?.split('&')[1] == '0' ? (
                  <EditOutlined style={{ marginRight: '5px' }} />
                ) : (
                  <CheckOutlined style={{ marginRight: '5px' }} />
                )
              }
              disabled={selectedRowKeys.length == 0}
              style={{ marginRight: '8px' }}
            >
              {permtype == 'model' && menuId?.split('&')[1] == '0' ? (
                <TextWidget>Permission.editPermission</TextWidget>
              ) : (
                <TextWidget>Permission.HaveAuthority</TextWidget>
              )}
            </Button>
            <Button
              onClick={() => onEditor(false)}
              icon={
                permtype == 'model' && menuId?.split('&')[1] == '0' ? (
                  <EyeOutlined style={{ marginRight: '5px' }} />
                ) : (
                  <CloseOutlined style={{ marginRight: '5px' }} />
                )
              }
              disabled={selectedRowKeys.length == 0}
            >
              {permtype == 'model' && menuId?.split('&')[1] == '0' ? (
                <TextWidget>Permission.viewPermissions</TextWidget>
              ) : (
                <TextWidget>Permission.noPermission</TextWidget>
              )}
            </Button>
          </div>
          <Input
            style={{ width: 300, height: '32px' }}
            placeholder={getMessage(
              'Permission.pleaseEnterTheUserNameToQuery',
            )}
            value={searchText}
            onChange={onChangeSearch}
            // onSearch={onSearch}
            onPressEnter={onSearch}
            suffix={
              <SearchOutlined
                onClick={onSearch}
                style={{ color: 'rgb(170, 170, 170)', cursor: 'pointer;' }}
              />
            }
          />
        </div>

        <Table {...tableProps} />
        {
          list.length ? (
            <div style={{ marginTop: 20 }}>
              <Pagination
                refreshData={() => {
                  onSearch && onSearch()
                }}
                pageRefresh={true}
                pagination={{
                  current: pageIndex,
                  pageSize: pageSize,
                  total: list.length,
                  showQuickJumper: true,
                  showSizeChanger: true,
                  pageSizeOptions: [10, 20, 30, 50, 100],
                  showLessItems: true,
                  // @ts-ignore
                  showTotal: true,
                }}
                onPageChange={({ current, pageSize }) => {
                  $pageIndex(current);
                  $pageSize(pageSize);
                }}
              />
            </div>
          ) : null
        }

        {permConfig.member.length ? (
          <MemberSelectCore
            className={'permissinMemberSelect'}
            {...memberSelectProps}
          />
        ) : (
          <></>
        )}
      </div>
    </div>
  );
});

export default Permission;
